package net.pm.core.service.impl;

import java.util.List;

import javax.annotation.Resource;

import net.pm.common.dao.GenericDao;
import net.pm.common.service.impl.GenericServicerImpl;
import net.pm.core.entities.db.Materiallog;
import net.pm.core.service.CollarMaterialServicer;
import net.pm.core.service.MateriallogServicer;

import org.springframework.stereotype.Service;

@Service("MateriallogServicer")
public class MateriallogServicerImpl extends GenericServicerImpl<Materiallog, Long> implements MateriallogServicer{

	@Resource(name="MateriallogDao")
	@Override
	public void setGenericDao(GenericDao<Materiallog, Long> genericDao) {
		super.genericDao = genericDao;
	}

	@Resource(name="CollarMaterialServicer")
	private CollarMaterialServicer collarMaterialServicer;
	
	
	@Override
	public List<Materiallog> findMateriallogByMaterialId(Long materialId) {
		final StringBuilder builder = new StringBuilder(
				" from Materiallog log where log.material.id = ? order by log.operationTime desc ");
		return super.findEntitiesByJpql(builder, materialId);
	}

	@Override
	public List<Materiallog> findMaterialogTop5ByCollarMaterialIds(
			List<Long> collarIds) {
		final StringBuilder builder = new StringBuilder(
				" from Materiallog log where log.collarmaterial.id in (0 ");
		for(Long collarId : collarIds){
			builder.append(" , ").append(collarId);
		}
		builder.append(" )  order by log.operationTime desc");
		return super.findPagerByJpql(5, 1, builder).getResult();
	}

	@Override
	public List<Materiallog> findMaterialogByCollarMaterialIds(List<Long> collarIds) {
		final StringBuilder builder = new StringBuilder(
				" from Materiallog log where log.collarmaterial.id in (0 ");
		for(Long collarId : collarIds){
			builder.append(" , ").append(collarId);
		}
		builder.append(" ) order by log.operationTime desc ");
		return super.findEntitiesByJpql(builder);
	}

	@Override
	public List<Materiallog> findMaterialogTop5ByProductId(Long productId) {
		List<Long> collarIds = collarMaterialServicer.findCollarIdsByProductId(productId); 
		return this.findMaterialogTop5ByCollarMaterialIds(collarIds);
	}

	@Override
	public List<Materiallog> findMaterialogByProductId(Long productId) {
		List<Long> collarIds = collarMaterialServicer.findCollarIdsByProductId(productId); 
		return this.findMaterialogByCollarMaterialIds(collarIds);
	}

}
